package cn.js.service.impl;


import cn.js.domain.User;
import cn.js.domain.entity.LoginUser;
import cn.js.mapper.MenuMapper;
import cn.js.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private MenuMapper menuMapper;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (ObjectUtils.isEmpty(username)) {
            throw new InternalAuthenticationServiceException("");
        }

        //1、查询用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", username);
        User user = userMapper.selectOne(queryWrapper);
        if(user==null){
            throw new  UsernameNotFoundException("");
        }


        //如果没有查询到用户，就抛出异常
//        if (Objects.isNull(user)) {
//            throw new RuntimeException("用户名或密码错误");
//        }
        //2、赋予用户对应的权限信息:目前写死了，项目中通过数据库查询出来
//        List<String> authorities = new ArrayList<>();
//        authorities.add("test");
//        authorities.add("select");
        //改用查询数据库
        List<String> strings = menuMapper.selectPermsByUserId(user.getId());

        //如果有，把数据封装成UserDetails对象返回
        //4.把权限封装进UserDetails对象中
        return new LoginUser(user,strings);

    }
}